import setToken from "@/utils/auth";
import axios from 'axios'
import Quill from "quill";
let fontFamily = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'sans-serif'];
Quill.imports['formats/font'].whitelist = fontFamily;
Quill.register(Quill.imports['formats/font'])


let Size = Quill.import('attributors/style/size')
Size.whitelist = ['14px', '15px', '16px', '17px', '18px', '20px','24px']
Quill.register(Size, true)


let toolBars = [
    [{
        size: Size.whitelist
    }], // 字体大小
    [{
        font: fontFamily
    }], // 字体种类

    [{
        header: [1, 2, 3, 4, 5, 6, false]
    }], // 标题
    // ["clean"], // 清除文本格式
    ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
    // ['blockquote', 'code-block'], // 引用  代码块
    [{
        header: 1
    }, {
        header: 2
    }], // 1、2级标题
    [{
        list: 'ordered'
    }], // 有序、无序列表
    // [{
    //     script: 'sub'
    // }, {
    //     script: 'super'
    // }], // 上标/下标
    [{
        indent: '-1'
    }, {
        indent: '+1'
    }], // 缩进
    [{
        'direction': 'rtl'
    }], // 文本方向
    [{
        color: []
    }], // 字体颜色、字体背景颜色
    [{
        align: []
    }], // 对齐方式
    // ['clean'], // 清除文本格式
    ['link', 'image'] // 链接、图片、视频-----['link', 'image', 'video']
];
const handlers = {
    image: function image() {
        var fileInput = this.container.querySelector('input.ql-image[type=file]');
        if (fileInput === null) {
            fileInput = document.createElement('input');
            fileInput.setAttribute('type', 'file');
            // 设置图片参数名
            fileInput.setAttribute('name', 'flie');
            // 可设置上传图片的格式
            fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
            fileInput.classList.add('ql-image');
            // 监听选择文件
            fileInput.addEventListener('change', _ => {
                let formData = new FormData();
                let token = setToken.getToken();
                formData.append("file", fileInput.files[0], fileInput.files[0].name);
                axios({
                        method: "post",
                        url: "/api/upload",
                        data: formData,
                        headers: {
                            Authorization: "Bearer " + token
                        },
                    })
                    .then((res) => {
                        let length = this.quill.getSelection(true).index;
                        this.quill.insertEmbed(length, 'image', res.data.data);
                        this.quill.setSelection(length + 1)
                    })
                    .catch((error) => {

                    });
            });
            this.container.appendChild(fileInput);
        }
        fileInput.click();
    }
};

export {
    toolBars,
    handlers
}